import { ElLoading } from 'element-plus';
import 'element-plus/es/components/loading/style/css';
import type { dsqRequestConfig } from './type';
import type { AxiosResponse } from 'axios';
import type { IDsqThisType } from './type';
export default function (dsqThis: IDsqThisType): void {
  //单个请求实例的拦截器
  dsqThis.instance.interceptors.request.use(
    dsqThis.interceptors?.requestInterceptor,
    dsqThis.interceptors?.requestInterceptorCatch
  );
  dsqThis.instance.interceptors.response.use(
    dsqThis.interceptors?.responseInterceptor,
    dsqThis.interceptors?.responseInterceptorCatch
  );
  //添加所有实例都有的拦截器
  dsqThis.instance.interceptors.request.use(
    (config: dsqRequestConfig) => {
      console.log('请求成功的拦截');
      if (dsqThis.showLoading) {
        dsqThis.loading = ElLoading.service({
          lock: true,
          text: '正在加载中...',
          background: 'rgba(0, 0, 0, 0.5)'
        });
      }
      return config;
    },
    (err: any) => {
      console.log('请求失败的拦截');
      return err;
    }
  ),
    dsqThis.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        //响应成功就移除loading
        setTimeout(() => {
          dsqThis.loading?.close();
        }, 500);
        console.log('响应成功的拦截');
        return res.data;
      },
      (err: any) => {
        setTimeout(() => {
          dsqThis.loading?.close();
        }, 1000);
        console.log('响应失败的拦截');
        return err;
      }
    );
}
